﻿using PaddleOCRSharp;
using System;
using System.Drawing;
using System.Linq;
using System.Text;

namespace DevelopTool_OCR_Modular
{
    /// <summary>
    /// ocr帮助类
    /// </summary>
    public static class Ocr
    {

        private static PaddleOCREngine engine;

        private static PaddleOCREngine GetEngine()
        {
            if (engine == null)
            {

                OCRModelConfig config = null;
                OCRParameter oCRParameter = new OCRParameter();

                //建议程序全局初始化一次即可，不必每次识别都初始化，容易报错。
                engine = new PaddleOCREngine(config, oCRParameter);
            }
            return engine;
        }

        public static void DisposeEngine()
        {
            if (engine != null)
                engine.Dispose();
        }


        /// <summary>
        /// 识别图片内容并返回文本（适用于单次识别）
        /// </summary>
        /// <param name="image">原始图片对象</param>
        /// <param name="markImage">标记识别路径后的图片对象</param>
        /// <returns></returns>
        public static string GetTextByImg(Image image, out Image markImage)
        {
            try
            {
                //中英文模型V4
                OCRModelConfig config = new OCRModelConfig();
                string modelPathroot = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

                modelPathroot += @"\inference\";
                config.det_infer = modelPathroot + "ch_PP-OCRv4_det_infer";
                config.cls_infer = modelPathroot + "ch_ppocr_mobile_v2.0_cls_infer";
                config.rec_infer = modelPathroot + "ch_PP-OCRv4_rec_infer";
                config.keys = modelPathroot + "ppocr_keys.txt";

                //OCR参数
                OCRParameter oCRParameter = new OCRParameter();

                //初始化OCR引擎
                PaddleOCREngine engine = new PaddleOCREngine(config, oCRParameter);

                OCRResult ocrResult = engine.DetectText(image);//识别内容

                markImage = (Image)image.Clone();//克隆原始图片

                StringBuilder sb = new StringBuilder();
                foreach (var item in ocrResult.TextBlocks)
                {
                    sb.AppendLine(item.Text);

                    using (Graphics g = Graphics.FromImage(markImage))
                    {
                        g.DrawPolygon(new Pen(Brushes.Red, 2), item.BoxPoints.Select(x => new PointF() { X = x.X, Y = x.Y }).ToArray());
                    }
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                markImage = null;
                return ex.Message;
            }
        }



        /// <summary>
        /// 识别图片内容并返回文本（适用于批量循环识别）
        /// </summary>
        /// <param name="imgPath">图片路径</param>
        /// <returns></returns>
        public static string GetTextByImgPath(string imgPath)
        {
            try
            {
                OCRResult ocrResult = GetEngine().DetectText(imgPath);//识别内容
                StringBuilder sb = new StringBuilder();
                foreach (var item in ocrResult.TextBlocks)
                {
                    sb.AppendLine(item.Text);
                }
                return sb.ToString();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

    }
}
